<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------
quanli_require('module/base/customer/customerManage.class.php');
quanli_require('module/base/system/itemHandler.class.php');
quanli_require('module/func/eai.func.php');

/**
 * 账户异动类
 * @package  module/base/customer
 * @author   allen.qiang
 * @version 1.0
 */

class financeChange {

    private $dbca;

    public function __construct( &$dbca ) {
        $this->dbca = $dbca;
    }

    /**
     * 查询账户异动信息
     * @param array  $arg_array                          查询参数数组
     * $arg_array = array(
    'sortname' => string, 排序字段
    'sortorder' => string, 排序方式
    'page' => int, 分页页数
    'rp' => int, 分页页数
     * )
     * @return array
     */
    public function searchFinanceInfo( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //流水号
        if (isset($arg_array['changeID']) && !empty($arg_array['changeID']) && is_numeric($arg_array['changeID'])) {
            $sql .= ' AND cfc.changeID = ?';
            $params_type .= 'i';
            $params_array[] = trim($arg_array['changeID']);
        }

        //客户名称
        if (isset($arg_array['custName']) && !empty($arg_array['custName'])) {
            $sql .= " AND cfc.custName LIKE '%" . trim($arg_array['custName']) . "%'";
        }

        //创建开始时间
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate'])) {
            $sql .= " AND cfc.createTime >= '" . $arg_array['startDate'] . "'";
        }
        //创建结束时间
        if (isset($arg_array['endDate']) && !empty($arg_array['endDate'])) {
            $sql .= " AND cfc.createTime <= '" . $arg_array['endDate'] . " 23:59:59'";
        }

        //异动状态
        if (isset($arg_array['changeStatus']) && !empty($arg_array['changeStatus']) && is_numeric($arg_array['changeStatus'])) {
            if($arg_array['changeStatus'] == 1) {
                $sql .= " AND cfc.changeAmount >= 0";
            }else{
                $sql .= " AND cfc.changeAmount < 0";
            }
        }

        //部门
        if (isset($arg_array['search_departmentID']) && !empty($arg_array['search_departmentID'])) {
            $sql .= " AND cm.departmentID = '" . $arg_array['search_departmentID'] . "'";
        }
        //销售员
        if (isset($arg_array['userID']) && !empty($arg_array['userID'])) {
            $sql .= " AND cm.userID = '" . $arg_array['userID'] . "'";
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
            if (isset($arg_array['changeStatus']) && !empty($arg_array['changeStatus']) && is_numeric($arg_array['changeStatus'])) {
                if($arg_array['changeStatus'] == 1) {
                    $suma_sql = $sql;
                    $sumb_sql = false;
                }else{
                    $sumb_sql = $sql;
                    $suma_sql = false;
                }
            }else{
                $suma_sql = $sql . ' AND cfc.changeAmount >= 0';
                $sumb_sql = $sql . ' AND cfc.changeAmount < 0';
            }
        }else{
            $suma_sql = ' WHERE cfc.changeAmount >= 0';
            $sumb_sql = ' WHERE cfc.changeAmount < 0';
        }
        $account_list = array(); //账户异动数据数组
        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM  cust_finance_change cfc
                               INNER JOIN company_master cm ON cfc.custID=cm.company_id' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }else{

                    $arg_array['count'] = $item_count;
                    //分页bug处理
                    if ($arg_array['count'] < $arg_array['rp']) {

                        $arg_array['page'] = 1;
                    }

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

                }
            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);
            }
            //应收
            if ($suma_sql){
                $search_sql = 'SELECT SUM(cfc.changeAmount) AS receivable FROM cust_finance_change cfc
                          INNER JOIN company_master cm ON cfc.custID=cm.company_id'. $suma_sql;
                $receivable = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $list['money']['receivable'] = $receivable[0]->receivable;
            }else{
                $list['money']['receivable'] = 0;
            }

            //实收
            if ($sumb_sql){
                $search_sql = 'SELECT SUM(cfc.changeAmount) AS receivable FROM cust_finance_change cfc
                          INNER JOIN company_master cm ON cfc.custID=cm.company_id'. $sumb_sql;
                $receivable = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $list['money']['receipts'] = $receivable[0]->receivable;
            }else{
                $list['money']['receipts'] = 0;
            }
            $list['money']['uncollected'] = $list['money']['receivable']+$list['money']['receipts'];


            //查询分类信息
            $search_sql = 'SELECT cfc.* FROM cust_finance_change cfc
                          INNER JOIN company_master cm ON cfc.custID=cm.company_id'. $sql;

            $account_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if ($account_array) {
                foreach ($account_array as $account) {
                    $account_list[] = array(
                        'uuid' => $account->uuid,
                        'timeStamp' => $account->timeStamp,
                        'creator' => $account->creator,
                        'createTime' => $account->createTime,
                        'editor' => $account->editor,
                        'changeID' => $account->changeID,
                        'custID' => $account->custID,
                        'custName' => $account->custName,
                        'saleCode' => $account->saleCode,
                        'paymentMethod' => $account->paymentMethod,
                        'changeAmount' => $account->changeAmount,
                        'remark' => $account->remark,
                        'changeStatus' => $account->changeStatus
                    );
                }
            }
            $list['account_list'] = $account_list;
            return $list;

        } catch (Exception $e) {
            error_log($e->getMessage());
            return null;
        }
    }


    /**
     * 添加或编辑账户异动
     * @param array $arg_array 参数数组
     * $arg_array = array ()
     * @return array
     */
    public function saveAccountChange( $arg_array ) {

        //用户名
        if (!isset($arg_array['custID']) || empty($arg_array['custID'])) {
            return array( 'code' => 400, 'message' => '请选择客户' );
        }

        //订单号不能为空
        if (!isset($arg_array['saleCode']) || empty($arg_array['saleCode'])) {
            return array( 'code' => 400, 'message' => '订单号不能为空' );
        }

        //请选择支付方式
        if (!isset($arg_array['paymentMethod']) || empty($arg_array['paymentMethod'])) {
            return array( 'code' => 400, 'message' => '请选择支付方式' );
        }

        //金额不能为空
        if (!isset($arg_array['changeAmount']) || empty($arg_array['changeAmount'])) {
            return array( 'code' => 400, 'message' => '金额不能为空' );
        }

        try {

            //获取当前创建时间
            $datetime = date("Y-m-d h:i:s");

            $save_array = new entity('cust_finance_change');

            if (isset($arg_array['changeID']) && !empty($arg_array['changeID'])) { //编辑
                $save_array->changeID = $arg_array['changeID'];
                if (!$this->dbca->fetch($save_array)) {
                    return array( 'code' => 406, 'message' => '编辑对象没有找到');
                }
            }

            $save_array->creator = $arg_array['creator'];
            $save_array->createTime = $datetime;
            $save_array->custID = $arg_array['custID'];
            $save_array->custName = $arg_array['custName'];
            $save_array->saleCode = $arg_array['saleCode'];
            $save_array->paymentMethod = $arg_array['paymentMethod'];
            $save_array->changeAmount = $arg_array['changeAmount'];
            $save_array->remark = $arg_array['remark'];

            if (isset($arg_array['changeStatus']) && !empty($arg_array['changeStatus'])) {
                $save_array->changeStatus = $arg_array['changeStatus'];
            } else {
                $save_array->changeStatus = 1;
            }

            $this->dbca->save($save_array,'customer');

            return array( 'code' => 200, 'message' => '保存成功' );

        } catch (Exception $e) {
            error_log($e->getMessage());
            return array( 'code' => 500, 'message' => '系统异常,请与系统管理员联系' );
        }
    }

}